package ioc

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"jk-time/webook/internal/web"
	ijwt "jk-time/webook/internal/web/jwt"
	"jk-time/webook/internal/web/middleware"
	"jk-time/webook/pkg/ginx"
	"jk-time/webook/pkg/ginx/middlewares/metrics"
	"strings"
	"time"
)

// InitMiddlewares -> mdls
func InitGin(mdls []gin.HandlerFunc, userHdl *web.UserHandler,
	oauth2 *web.OAuth2WechatHandler, artHdl *web.ArticleHandler, gitHdl *web.OAuth2GithubHandler) *gin.Engine {
	server := gin.Default()
	server.Use(mdls...)
	userHdl.RegisterRouters(server)
	oauth2.RegisterRoutes(server)
	artHdl.RegisterRouters(server)
	gitHdl.RegisterRoutes(server)

	o := web.ObservabilityHandler{}
	o.RegisterRouters(server)
	return server
}
func InitMiddlewares(handler ijwt.Handler) []gin.HandlerFunc {
	ginx.NewCounter("code_count", "webook",
		"biz_code", "统计HTTP的code数量", "biz_code-1")
	return []gin.HandlerFunc{
		corsHdl(),
		metrics.NewMiddlewareBuilder("gin_middle", "webook",
			"gin_http", "统计GIN的HTTP接口", "gin-1").Build(),
		//middleware.NewLoginJWTMiddlewareBuilder(handler).
		middleware.NewLoginJWTMiddlewareBuilder(handler).
			IgnorePaths("/debug").
			IgnorePaths("/users/login").
			IgnorePaths("/users/signup").
			IgnorePaths("/users/login_sms/code/send").
			IgnorePaths("/users/login_sms").
			IgnorePaths("/users/login_sms").
			IgnorePaths("/users/refresh_token").
			IgnorePaths("/oauth2").
			IgnorePaths("/articles").
			IgnorePaths("/pub").
			IgnorePaths("/test/metrics").
			CheckLogin(),
		//ratelimit.NewBuilder(cmd, time.Minute, 100).Build(),
		func(context *gin.Context) {
			context.Set("claims", &ijwt.UserClaims{
				Uid: 1,
			})
		},
	}
}
func corsHdl() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowHeaders: []string{"Content-Type", "Authorization"},
		//是否允许携带用户验证信息
		AllowCredentials: true,
		//不加这个，前端拿不到
		ExposeHeaders: []string{"X-Jwt-Token", "X-refresh-Token"},
		//是否允许来源
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "")
		},
		MaxAge: 12 * time.Hour,
	})
}
